package com.zw.yzk.kabu.view.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.adapter.ExhibitionDetailsAdapter;
import com.zw.yzk.kabu.adapter.header.HeaderHelper;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.internal.component.DaggerExhibitionDetailsComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.ExhibitionDetailsModule;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToolbarBuilder;
import com.zw.yzk.kabu.model.ConfirmTicketModel;
import com.zw.yzk.kabu.model.ExhibitionDetailsModel;
import com.zw.yzk.kabu.presenter.ExhibitionDetailsPresenter;
import com.zw.yzk.kabu.utils.ResUtils;
import com.zw.yzk.kabu.utils.TimeFormatUtils;
import com.zw.yzk.kabu.view.activity.imagedetails.ImageDetailsActivity;
import com.zw.yzk.kabu.view.view.ExhibitionDetailsView;
import com.zw.yzk.kabu.view.widget.BuyTicketDialog;


import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;

/**
 * Created by zhanwei on 2017/2/6.
 */

public class ExhibitionDetailsActivity extends BaseActivity implements ExhibitionDetailsView {

    @Bind(R.id.details)
    RecyclerView details;
    private ImageView coverImage;
    private TextView exhibitionName;
    private TextView exhibitionTime;
    private TextView exhibitionAddress;
    private TextView exhibitionPrice;
    private CheckBox concern;
    private TextView buyTicket;
    private TextView detailsAddress;
    private TextView detailsPlace;
    private TextView detailsTime;
    private TextView detailsPrice;
    private TextView detailsRemark;

    @Inject
    ExhibitionDetailsPresenter presenter;
    private ExhibitionDetailsAdapter adapter;
    private ExhibitionDetailsModel detailsModel;

    @Override
    public int getLayoutId() {
        return R.layout.activity_exhibition_details;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {
        ToolbarBuilder
                .createBuilder(this)
                .setTitle(getResources().getString(R.string.exhibition_details))
                .build();
    }

    @Override
    public void initComponent() {
        DaggerExhibitionDetailsComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .exhibitionDetailsModule(new ExhibitionDetailsModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initRecycleView();
        getExhibitionDetails();
        LoadingDialogManager.getInstance().showLoadingDialog(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    public void getExhibitionDetailsSuccess(ExhibitionDetailsModel model) {
        this.detailsModel = model;
        //设置基本信息
        setBaseInfo(model);
        //设置漫展嘉宾信息
        setGuestInfo(model);
        //设置按钮状态
        setButtonStatus(model.isCollected(), model.isBuyable());
    }

    @Override
    public boolean getCollectStatus() {
        return concern.isChecked();
    }

    @Override
    public void collectFailed() {
        setConcernStatus(!concern.isChecked());
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecycleView() {
        details.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new ExhibitionDetailsAdapter(null);
        View header = LayoutInflater.from(this).inflate(R.layout.recycler_header_exhibition_details, details, false);
        initHeader(header);
        //给RecyclerView添加头部
        HeaderHelper.createHelper(adapter).addHeader(details, header);
    }

    /**
     * 初始化Header
     *
     * @param header header
     */
    private void initHeader(View header) {
        coverImage = (ImageView) header.findViewById(R.id.exhibition_image);
        exhibitionName = (TextView) header.findViewById(R.id.exhibition_title);
        exhibitionTime = (TextView) header.findViewById(R.id.date);
        exhibitionAddress = (TextView) header.findViewById(R.id.place);
        exhibitionPrice = (TextView) header.findViewById(R.id.price);
        concern = (CheckBox) header.findViewById(R.id.concern);
        buyTicket = (TextView) header.findViewById(R.id.buy_ticket);
        detailsAddress = (TextView) header.findViewById(R.id.address);
        detailsPlace = (TextView) header.findViewById(R.id.details_place);
        detailsTime = (TextView) header.findViewById(R.id.time);
        detailsPrice = (TextView) header.findViewById(R.id.details_price);
        detailsRemark = (TextView) header.findViewById(R.id.remark);

        concern.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                collectExhibition();
            }
        });
        buyTicket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new BuyTicketDialog.Builder(ExhibitionDetailsActivity.this)
                        .setImage(detailsModel.getCoverImage())
                        .setDeadLine(detailsModel.getEndTime())
                        .setPropertyList(detailsModel)
                        .setConfirmListener(new BuyTicketDialog.OnConfirmClickedListener() {
                            @Override
                            public void onClick(int count, ExhibitionDetailsModel.Property property) {
                                if (property == null) {
                                    return;
                                }
                                ConfirmTicketModel model = new ConfirmTicketModel();
                                model.setTicketId(property.getId());
                                model.setExhibitionId(property.getExhibitionId());
                                model.setPrice(property.getOriginalPrice());
                                model.setCount(count);
                                model.setType(property.getContent());
                                model.setExhibitionName(detailsModel.getName());
                                model.setExhibitionTime(detailsModel.getStartTime());
                                model.setImage(detailsModel.getCoverImage());

                                Intent intent = new Intent(ExhibitionDetailsActivity.this, ConfirmExhibitionTicketActivity.class);
                                intent.putExtra(ActivityConstant.CONFIRM_EXHIBITION_TICKET_DATA, model);
                                startActivity(intent);
                            }
                        })
                        .build()
                        .showAtLocation(ExhibitionDetailsActivity.this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
            }
        });
    }

    /**
     * 设置展会信息
     */
    private void setBaseInfo(final ExhibitionDetailsModel model) {
        Glide.with(this)
                .load(model.getCoverImage())
                .error(R.drawable.im_default)
                .into(coverImage);
        coverImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Rect rect = new Rect();
                coverImage.getGlobalVisibleRect(rect);
                ImageDetailsActivity.startDetailsActivity(ExhibitionDetailsActivity.this, model.getCoverImage(), rect);
            }
        });

        exhibitionName.setText(model.getName());
        String timeDetails;
        try {
            timeDetails = TimeFormatUtils.stringDateFormat(model.getStartTime(), "yyyy-MM-dd HH:mm:ss", "yyyy年MM月dd日") + "-"
                    + TimeFormatUtils.stringDateFormat(model.getEndTime(), "yyyy-MM-dd HH:mm:ss", "MM月dd日");
        } catch (Exception e) {
            timeDetails = model.getStartTime() + "-" + model.getEndTime();
        }
        exhibitionTime.setText(timeDetails);
        exhibitionAddress.setText(model.getProvince() + " " + model.getCity() + " " + model.getDistrict() + " " + model.getAddress());
        if (!model.getPropertyList().isEmpty()) {
            exhibitionPrice.setText(ResUtils.formatCurrency(this, model.getPropertyList().get(0).getOriginalPrice()));
            detailsPrice.setText(getDetailsPrice(model.getPropertyList()));
        }
        detailsAddress.setText(model.getProvince() + " " + model.getCity() + " " + model.getDistrict() + " " + model.getAddress());
        detailsPlace.setText(model.getAddress());
        String time;
        try {
            time = TimeFormatUtils.stringDateFormat(model.getStartTime(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm") + "-"
                    + TimeFormatUtils.stringDateFormat(model.getEndTime(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm");
        } catch (Exception e) {
            time = model.getStartTime() + "-" + model.getEndTime();
        }
        detailsTime.setText(time);
        detailsRemark.setText(model.getRemark());
    }

    /**
     * 获取价格详情
     *
     * @param list 商品属性列表
     * @return
     */
    private String getDetailsPrice(List<ExhibitionDetailsModel.Property> list) {
        String result = "";
        for (ExhibitionDetailsModel.Property property : list) {
            result += property.getContent() + ResUtils.formatCurrency(property.getOriginalPrice()) + ";";
        }
        return result;
    }

    /**
     * 设置漫展嘉宾信息
     *
     * @param model
     */
    private void setGuestInfo(ExhibitionDetailsModel model) {
        adapter.refresh(model.getGuestList());
    }

    /**
     * 设置按钮点击状态
     *
     * @param isConcerned 是否关注
     * @param isBuyabale  是否可以购买
     */
    private void setButtonStatus(boolean isConcerned, boolean isBuyabale) {
        setConcernStatus(isConcerned);
        buyTicket.setEnabled(isBuyabale);
        buyTicket.setBackgroundResource(isBuyabale ? R.drawable.selector_btn_login : R.drawable.shape_btn_buy_ticket_unable);
    }

    /**
     * 设置关注漫展状态
     *
     * @param check
     */
    private void setConcernStatus(boolean check) {
        concern.setChecked(check);
        concern.setText(check ? R.string.has_concerned : R.string.concern_exhibition);
    }

    /**
     * 获取展会详情
     */
    private void getExhibitionDetails() {
        int id = getIntent().getIntExtra(ActivityConstant.EXHIBITION_DETAILS_ID, -1);
        presenter.getExhibitionDetails(id);
    }

    /**
     * 是否收藏展会
     */
    private void collectExhibition() {
        int id = getIntent().getIntExtra(ActivityConstant.EXHIBITION_DETAILS_ID, -1);
        presenter.collectExhibition(id, concern.isChecked());
        setConcernStatus(concern.isChecked());
    }

}
